package msu.ml.data;

import weka.core.*;
import weka.classifiers.*;
import msu.ml.gis.*;
import msu.ml.core.*;
import java.util.*;
import java.io.*;

/**
 * This class has not yet been implemented.
 *
 * @author Reginald M Mead
 * @version 1.0
 */
public class GISPostProcessor extends DataPostProcessorAdapter
{
	public void endExperiment()
	{
		Experiment exp = getExperiment();
		Classifier c = exp.getClassifier();
		IDataProvider p = exp.getDataProvider();

		if(p instanceof DbCrossValidationDataProvider)
		{
			DbCrossValidationDataProvider dbp = 
				(DbCrossValidationDataProvider)p;

			System.out.println("Creating Shapefiles...");

			HashSet<String> features = exp.getFeatures();
			boolean az = !features.contains("1");
			boolean ra = !features.contains("2");
			features.add("1");
			features.add("2");

			AttributeRemovalPreProcessor filter = new
				AttributeRemovalPreProcessor();
			filter.setInvertSelection(true);
			String featureString = features.toString();
			filter.setAttributeIndices(featureString.substring(1,
						featureString.length() - 1));

			ArrayList<IDataPreProcessor> filters = new
				ArrayList<IDataPreProcessor>();
			filters.add(filter);
			DatabaseCache cache = dbp.getCache();

			File imageDir = new File(exp.getName() + "_gis");
			imageDir.mkdir();

			for(String file : dbp.getFileNames())
			{
				System.out.println(file + ".shp");
				Shapefile sfile = new Shapefile(40.1506, -89.3369);
				sfile.setShapeType(5);

				try
				{

					NxInstances richData = cache.retrieve(file, filters);
					NxInstances data = new NxInstances(richData);
					if(ra) data.deleteAttributeAt(1);
					if(az) data.deleteAttributeAt(0);

					for(int i = 0; i < data.numAttributes(); i++)
					{
						Attribute attr = data.attribute(i);
						DBFAttributeHeader header = new DBFAttributeHeader(attr.name(), 'N', 6);
						sfile.getHeaders().add(header);
					}

					for(int i = 0; i < data.numInstances(); i++)
					{
						double [] dist = c.distributionForInstance(data.instance(i));
						Instance inst = richData.instance(i);

						PulseVolumeShape shape = new PulseVolumeShape(sfile,
								inst.value(0), (int)inst.value(1));

						ArrayList<DBFAttributeHeader> headers = sfile.getHeaders();
						for(int j = 0; j < headers.size(); j++)
						{
							DBFAttribute dbfAttr = new DBFAttribute(headers.get(j));
							if(j == headers.size() - 1)
								dbfAttr.setValue(new Double(dist[1]));
							else
								dbfAttr.setValue(new Double(inst.value(j)));

							shape.addAttribute(dbfAttr);
						}

						sfile.addShape(shape);
					}

					ShapefileWriter writer = new ShapefileWriter();
					writer.write(sfile, imageDir.getName() + File.separatorChar + file);

				}
				catch(Exception e)
				{
					System.out.println(e);
					e.printStackTrace();
				}
			}
		}
	}
}
